using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using WASM.WebSite.Models;
using Microsoft.Samples.ServiceHosting.StorageClient;

namespace WASM.WebSite.Controllers
{
	[Authorize]
	public class QueueController : Controller
	{
		public ActionResult List(Guid storageId)
		{
			ViewData["storageId"] = storageId;
			ViewData.Model = QueueRepository.Create(storageId).QueueList();
			return View();
		}

		public ActionResult QueueDelete(Guid storageId, string storageBoxId)
		{
			QueueRepository.Create(storageId).QueueDelete(storageBoxId);
			return RedirectToAction("List", new { storageId = storageId });
		}

		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult QueueCreate(Guid storageId)
		{
			ViewData["storageId"] = storageId;
			return View();
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult QueueCreate(Guid storageId, string storageBoxId)
		{
			QueueValidate(storageId, storageBoxId);

			if (ModelState.IsValid)
			{
				QueueRepository.Create(storageId).QueueCreate(storageBoxId);
				return RedirectToAction("List", new { storageId = storageId });
			}
			else
			{
				return View();
			}
		}

		private void QueueValidate(Guid storageId, string queueName)
		{
			if (String.IsNullOrEmpty(queueName))
				ModelState.AddModelError("storageBoxId", "String Gueue Name is empty");
			else if (QueueRepository.Create(storageId).IsQueueExist(queueName))
				ModelState.AddModelError("storageBoxId", String.Format("Gueue [{0}] alredy exit", queueName));
		}

		public ActionResult MessageList(Guid storageId, string storageBoxId)
		{
			ViewData["storageId"] = storageId;
			ViewData["storageBoxId"] = storageBoxId;

			var messages = QueueRepository.Create(storageId).MessageList(storageBoxId);
			ViewData.Model = messages ?? new Message[0];
			return View();
		}

		public ActionResult MessageDelete(Guid storageId, string storageBoxId)
		{
			QueueRepository.Create(storageId).MessageDeleteTop(storageBoxId);
			return RedirectToAction("MessageList", new { storageId = storageId, storageBoxId = storageBoxId });
		}

		public ActionResult MessageCreate(Guid storageId, string storageBoxId, string messageContent)
		{
			QueueRepository.Create(storageId).MessageCreate(storageBoxId, messageContent);
			return RedirectToAction("MessageList", new { storageId = storageId, storageBoxId = storageBoxId });
		}
	}
}
